import streamlit as st
from pymongo import MongoClient
#  pip install -i https://pypi.tuna.tsinghua.edu.cn/simple streamlit
from conf import *
# 连接到MongoDB
#client = MongoClient("mongodb://localhost:27017/")
mongo_uri = f"mongodb://{username}:{password}@{ip}:{port}/{dbname}?authSource=admin"

# 创建MongoDB客户端
client = MongoClient(mongo_uri)
# 获取所有数据库的名称
#db_names = client.list_database_names()

# 创建下拉菜单，选择数据库
selected_db = dbname#st.selectbox("Select a database", db_names)
from bson.son import SON

def count_field_distribution(collection, field_name):
    # 连接到MongoDB，默认在本地运行的MongoDB实例
    # 聚合管道操作，用于统计每个字段取值的分布
    pipeline = [
        {"$group": {
            "_id": f"${field_name}",  # 使用字段值作为分组依据
            "count": {"$sum": 1}  # 对每个分组计数
        }},
        {"$sort": SON([("count", -1), ("_id", 1)])}  # 可选：按计数降序排序，再按字段值升序排序
    ]

    # 执行聚合管道操作
    results = collection.aggregate(pipeline)
    d = {}
    for result in results:
        d[result['_id']]=result['count']
    return d
    # 获取选定数据库中的所有集合名称
if selected_db:
    db = client[selected_db]
    collection_names = db.list_collection_names()
    btn1 = st.button("查询大小")
    if btn1:
        for s in collection_names:
            collection  = db[s]
            count = collection.count_documents({})

            st.text(f"{s}:{count}个")
    # 创建下拉菜单，选择集合
    selected_collection = st.selectbox("选择 collection", collection_names)
    topk = st.selectbox("取出几个", [10,20,30],0)
    # 创建文本输入框，输入查询
    query_text = st.text_input("输入查询语句 (JSON format)","{}")
    query_field = st.text_input("输入查询字段 ","platform")

    btn2= st.button("查询字段")

    if btn2 :
        coll_ob = db[selected_collection]
        dist = count_field_distribution(coll_ob,query_field)
        st.json(dist)

    # 创建按钮，执行查询
    if st.button("确定并运行"):
        if query_text:
            try:
                # 解析查询文本为JSON
                query = eval(query_text)
                # 执行查询并获取前10个结果
                results = db[selected_collection].find(query).limit(topk)
                # 显示结果
                for result in results:
                    st.write(result)
            except Exception as e:
                st.error(f"Error executing query: {e}")
        else:
            st.warning("输入查询.")

# streamlit run webMongo.py